package netbayServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.String.StringUtil;
import util.jQgrid.JQGridFormatterUtil;

import netbay.NetbayUtility;
import netbay.TransactionManager;
import netbay.UserManager;

/**
 * Servlet implementation class ManageAdminServlet
 */
public class ManageAdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ManageAdminServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init() {
		String configPath = getServletContext().getRealPath(
				"/WEB-INF/config.properties");
		NetbayUtility.init(configPath);
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as // 8-bit Unicode (e.g., for Czech characters)
		
        response.setContentType("text/json;charset=utf-8");
        HttpSession session = request.getSession();
        String url = "";
        String userId = ((!StringUtil.isNullOrEmpty((String)(session.getAttribute("userId")))) ? (String)session.getAttribute("userId"): "null");
        if(!(userId.equals("null"))){
        	url = "/ManageAdmin.jsp";
        }
        else{
        	url = "/Login.jsp";
        }
        try{
        	request.getRequestDispatcher(url).forward(request, response);
		} catch (Exception ex) {
            ex.printStackTrace();
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 request.setCharacterEncoding("UTF-8");
		 response.setContentType("text/json;charset=utf-8");
		 String userPath = request.getServletPath();
		 PrintWriter out = response.getWriter();
		 HttpSession session = request.getSession();
	     String strJson = "{}";
	     UserManager um = new UserManager();
	     if (userPath.equals("/ManageAdminServlet/DisplayAdmin")) {
		     
	    	 try {
	    		 String page = request.getParameter("page"); // get the requested page
		         String limit = request.getParameter("rows"); // get how many rows we want to have into the grid
		         String sidx = request.getParameter("sidx"); // get index row - i.e. user click to sort
		         String sord = request.getParameter("sord"); // get the direction
				 List result = null;
				 List all = null;
				 String id = (String) session.getAttribute("userId");
				 Integer count = 0;
				 result = um.displayUser(page, limit, sidx, sord);
				 all = um.displayUser();
				 count = all.size();
			
				 strJson = JQGridFormatterUtil.getJSON(Integer.parseInt(page), Integer.parseInt(limit), count, result);
	         } catch (Exception ex) {
	        	 strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ;
	         }
	         out.println(strJson);
	     }else if (userPath.equals("/ManageAdminServlet/DeleteAdmin")) {
	    	 try {
		    	 String rowdata = (String) request.getParameter("rowdata");
				 boolean result = false;
				 String username = um.getUsernameByid(Integer.parseInt(rowdata));
				 result = um.deleteAdmin(rowdata);
			 
				 if(result){
					 um.saveLog((String)session.getAttribute("userId"),UserManager.actionDeleteUser,username);
					 strJson = "{\"success\": \"\"}";
				 }else strJson = "{\"error\": \"Cannot delete user.\"}";
				//out.println(strJson);
	         } catch (Exception ex) {
	        	 strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ;
	         }
	         out.println(strJson);
	     }
	     
	}

}
